package com.naja.auth2clientfirst.support;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.security.oauth2.core.user.OAuth2User;

import java.util.HashSet;
import java.util.List;

/**
 * @auther wangjianying
 * @date 2023/12/28 14:57
 */
public class OAuth2AuthenticationTokenProvider implements AuthenticationProvider {
    ExpandUserAuthoritiesRepository userAuthoritiesRepository = ExpandUserAuthoritiesRepository.instance();

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        OAuth2AuthenticationToken oAuth2AuthenticationToken = (OAuth2AuthenticationToken) authentication;
        OAuth2User principal = oAuth2AuthenticationToken.getPrincipal();
        String name = principal.getName();
        List<String> userAuthoritiesRepositoryByName = userAuthoritiesRepository.findByName(name);
        if (userAuthoritiesRepositoryByName != null && !userAuthoritiesRepositoryByName.isEmpty()) {
            HashSet<GrantedAuthority> grantedAuthorities = new HashSet<>(oAuth2AuthenticationToken.getAuthorities());
            for (String s : userAuthoritiesRepositoryByName) {
                grantedAuthorities.add(new SimpleGrantedAuthority(s));
            }
            return new OAuth2AuthenticationToken(principal, grantedAuthorities, oAuth2AuthenticationToken.getAuthorizedClientRegistrationId());
        }
        return authentication;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return OAuth2AuthenticationToken.class.isAssignableFrom(authentication);
    }
}
